// File Name: key_ctrl.c
// Author: kukukukuku~
// Date: 2024-06-25

#include "./User/Key/inc/key_ctrl.h"

//按键对象
Key key[KEY_NUM] = 
{
    {KEY_UP_GPIO_PORT, KEY_UP_GPIO_PIN, 0, KEY_UP_LONG_JUDGE_NUM, 0, KEY_STATE_RELEASE, KEY_HANDLE_NONE, 0, 0, 0},
    {KEY_LEFT_GPIO_PORT, KEY_LEFT_GPIO_PIN, 0, KEY_LEFT_LONG_JUDGE_NUM, 0, KEY_STATE_RELEASE, KEY_HANDLE_NONE, 0, 0, 0},
    {KEY_DOWN_GPIO_PORT, KEY_DOWN_GPIO_PIN, 0, KEY_DOWN_LONG_JUDGE_NUM, 0, KEY_STATE_RELEASE, KEY_HANDLE_NONE, 0, 0, 0},
    {KEY_RIGHT_GPIO_PORT, KEY_RIGHT_GPIO_PIN, 0, KEY_RIGHT_LONG_JUDGE_NUM, 0, KEY_STATE_RELEASE, KEY_HANDLE_NONE, 0, 0, 0},
    {KEY_MID_GPIO_PORT, KEY_MID_GPIO_PIN, 0, KEY_MID_LONG_JUDGE_NUM, 0, KEY_STATE_RELEASE, KEY_HANDLE_NONE, 0, 0, 0},
};

uint8_t keyAllReleaseFlag;  //所有按键全部松开标志
uint8_t keyLockFlag;        //按键锁定标志

uint16_t keyClickBeep;  //按键短按蜂鸣时间
uint16_t keyLongBeep;   //按键长按蜂鸣时间

/**
 * @brief   Key初始化
 * @param   None
 * @retval  None
 * @note    静态函数
*/
static void key_init(void)
{
    gpio_init_type gpioInitStruct = 
    {
        .gpio_pins           = KEY_UP_GPIO_PIN,
        .gpio_out_type       = GPIO_OUTPUT_PUSH_PULL,
        .gpio_pull           = GPIO_PULL_UP,
        .gpio_mode           = GPIO_MODE_INPUT,
        .gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER,
    };
    
    //Key GPIO初始化
    crm_periph_clock_enable(KEY_GPIO_CRM, TRUE);
    gpio_init(KEY_UP_GPIO_PORT, &gpioInitStruct);
    gpioInitStruct.gpio_pins = KEY_LEFT_GPIO_PIN;
    gpio_init(KEY_LEFT_GPIO_PORT, &gpioInitStruct);
    gpioInitStruct.gpio_pins = KEY_DOWN_GPIO_PIN;
    gpio_init(KEY_DOWN_GPIO_PORT, &gpioInitStruct);
    gpioInitStruct.gpio_pins = KEY_RIGHT_GPIO_PIN;
    gpio_init(KEY_RIGHT_GPIO_PORT, &gpioInitStruct);
    gpioInitStruct.gpio_pins = KEY_MID_GPIO_PIN;
    gpio_init(KEY_MID_GPIO_PORT, &gpioInitStruct);
    
    //Key TMR初始化
    crm_periph_clock_enable(KEY_TMR_CRM, TRUE);
    tmr_base_init(KEY_TMR, KEY_TMR_PR, KEY_TMR_DIV);
    tmr_cnt_dir_set(KEY_TMR, TMR_COUNT_UP);
    tmr_clock_source_div_set(KEY_TMR, TMR_CLOCK_DIV1);
    tmr_period_buffer_enable(KEY_TMR, TRUE);
    tmr_flag_clear(KEY_TMR, TMR_OVF_FLAG);
    tmr_interrupt_enable(KEY_TMR, TMR_OVF_INT, TRUE);
    tmr_counter_enable(KEY_TMR, FALSE);
    
    //Key NVIC初始化
    nvic_irq_enable(KEY_TMR_IRQ, 0, 0);
}


/**
 * @brief   Key配置
 * @param   None
 * @retval  None
 * @note    None
*/
void key_config(void)
{
    key_init();
    
    keyClickBeep = KEY_CLICK_BEEP;
    keyLongBeep = KEY_LONG_BEEP;
}
